/**
 * @Title:业务实现
 * @Description:数据字典管理
 * Copyright 2018 GemFrame技术团队 http://www.gemframe.cn
 * Company: DianShiKongJian (Beijing) Technology Co., Ltd.
 * @author nine
 * @date 2018-11-1 16:06:06
 * @version V1.0
 *
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cn.gemframe.service.impl;

import cn.gemframe.common.constants.Constants;
import cn.gemframe.common.enums.GemPasswordType;
import cn.gemframe.constant.GemConstant;
import cn.gemframe.dao.GemUserMapper;
import cn.gemframe.dao.GemUserRoleMapper;
import cn.gemframe.exception.GemException;
import cn.gemframe.exception.status.GemErrorStatus;
import cn.gemframe.mapper.GemBeanMapper;
import cn.gemframe.po.GemUser;
import cn.gemframe.po.GemUserRole;
import cn.gemframe.response.ResultData;
import cn.gemframe.service.GemUserRoleService;
import cn.gemframe.service.GemUserService;
import cn.gemframe.utils.GemIdUtlis;
import cn.gemframe.utils.GemJsonUtils;
import cn.gemframe.utils.GemPasswdUtil;
import cn.gemframe.utils.GemStringUtlis;
import cn.gemframe.vo.GemUserVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @Title:用户业务实现
 * @Description:数据字典管理
 * @author nine
 * @date 2018-11-1 16:06:06
 * @version V1.0
 */
@Slf4j
@Service
//捕获非检查性异常
@Transactional(rollbackFor = Exception.class)
public class GemUserServiceImpl implements GemUserService {

	@Autowired
    private GemUserRoleService userRoleService;

	@Autowired
	private GemUserMapper gemUserMapper;

	@Autowired
	private GemUserRoleMapper userRoleMapper;

	@Override
	public GemUserVo save(GemUserVo userVo) {
		String password = getPassWord(userVo.getPassword()
                ,String.valueOf(userVo.getPasstype())
                ,userVo.getUsername(),userVo.getIdcard());
		if(null == password){
			log.error("---生成密码失败,password:{}",password);
			return null;
		}
        Long userId = GemIdUtlis.Id();
        userVo.setId(userId);
        userVo.setPassword(password);
        userVo.setCreateTime(new Date());
        userVo.setUpdateTime(new Date());

        log.error("========="+count(userVo));
        GemUser user = GemJsonUtils.classToClass(userVo, GemUser.class);
		//开始保存用户
		if(!ResultData.checkDBOperResult(gemUserMapper.insert(user))){
            log.error("---保存用户失败,user:{}",user);
			return null;
		}

        //保存用户成功，开始保存用户角色关系
        Long[] roles = userVo.getRoleIds();
        if(roles!=null && roles.length>0) {
            for (Long roleId : roles) {
                GemUserRole userRole = new GemUserRole();
                userRole.setId(GemIdUtlis.Id());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                if(!ResultData.checkDBOperResult(userRoleMapper.insert(userRole))){
                    log.error("---保存用户角色关联关系失败,UserRole:{}",userRole.toString());
                    throw GemException.builder().code(1L).msg("s").build();
                }
            }
        }
		return userVo;
	}

	@Override
	public Integer delete(Long[] ids){

        if(ids!=null && ids.length>0) {
            for (Long id : ids) {
                delete(id);
            }
			return ResultData.SUCCESS;
        }
        return null;
	}

	@Override
	public Integer delete(Long id) {
		if(!ResultData.checkDBOperResult(gemUserMapper.deleteByPrimaryKey(id))){
			log.error("---删除失败,id:{}",id);
			throw new GemException(GemErrorStatus.DB_DELETE_ERROR);
		}
        return ResultData.SUCCESS;
	}

	@Override
	public GemUserVo update(GemUserVo userVo) {
        //修改用户实体表内容
        userVo.setUpdateTime(new Date());
        GemUser user = GemJsonUtils.classToClass(userVo, GemUser.class);
        Integer returnCount = gemUserMapper.updateByPrimaryKeySelective(user);
        //维护用户和角色的关系
//        userRoleService.updateUserToRole(userVo.getId(),userVo.getRoleIds());
        return userVo;

	}


	@Override
	public List<GemUserVo> pagelist(Example example, Integer pageNum, Integer pageSize) {
		List<GemUser> list = gemUserMapper.selectByExample(example);
		List<GemUserVo> resultList = Lists.newArrayList();
		GemBeanMapper.copy(list,resultList);
		return resultList;
	}

	@Override
	public GemUserVo info(Long id) {
	return null;
}

    @Override
    public Integer count(GemUserVo userVo) {
        GemUser user = GemJsonUtils.classToClass(userVo, GemUser.class);
        return gemUserMapper.selectCount(user);
    }

    @Override
	public List<GemUserVo> list(Example example) {
		List<GemUser> list = gemUserMapper.selectByExample(example);
		List<GemUserVo> resultList = Lists.newArrayList();
		GemBeanMapper.copy(list,resultList);
		return resultList;
	}

	private String getPassWord(String password,String type,String username,String idcard) {
		if(null != password && GemStringUtlis.isNotBlank(password)){
			return GemPasswdUtil.encode(password);
		}

		if(GemStringUtlis.isNotBlank(type) && type.length()>0) {
			if(type.equalsIgnoreCase(String.valueOf(GemPasswordType.DEFAULT.getValue()))) {
				return GemPasswdUtil.encode(Constants.DEF_PASS_WORD);
			}
			if(type.equalsIgnoreCase(String.valueOf(GemPasswordType.USERNAME.getValue()))) {
				if(null == username || GemStringUtlis.isBlank(username)){
					log.error("---与用户名相同密码生成失败,username:{}",username);
					return null;
				}
				return GemPasswdUtil.encode(username);
			}
			if(type.equalsIgnoreCase(String.valueOf(GemPasswordType.IDCARDLAST8.getValue()))) {
				if(null == idcard || idcard.length() < GemConstant.Number.EIGHT){
					log.error("---身份证后8位密码生成失败,idcard:{}",idcard);
					return null;
				}
				return GemPasswdUtil.encode(idcard.substring(idcard.length() - GemConstant.Number.EIGHT, idcard.length()));
			}
		}

		return null;
	}

    @Override
    public Integer existUser(GemUserVo userVo) {
        Example example = new Example(GemUser.class);
        Example.Criteria createCriteria = example.createCriteria();
        String userName = userVo.getUsername();
        return null;
    }
}
